package cn.schoolwow.quickflow.service.quickFlow;

import cn.schoolwow.quickflow.domain.FlowConfig;
import cn.schoolwow.quickflow.service.quickFlow.execute.QuickFlowExecuteOperationImpl;
import cn.schoolwow.quickflow.service.quickFlow.getData.QuickFlowGetDataOperationImpl;
import cn.schoolwow.quickflow.service.quickFlow.option.QuickFlowOptionImpl;
import cn.schoolwow.quickflow.service.quickFlow.putData.QuickFlowPutDataOperationImpl;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 代理模式对象
 */
public class QuickFlowInvocationHandler implements InvocationHandler {
    private Object[] interfaceInstanceArray;

    public QuickFlowInvocationHandler(FlowConfig flowConfig) {
        interfaceInstanceArray = new Object[]{
                new QuickFlowOptionImpl(flowConfig),
                new QuickFlowGetDataOperationImpl(flowConfig),
                new QuickFlowPutDataOperationImpl(flowConfig),
                new QuickFlowExecuteOperationImpl(flowConfig)
        };
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        String interfaceName = method.getDeclaringClass().getSimpleName();
        for(Object interfaceInstance:interfaceInstanceArray){
            Class interfaceClass = interfaceInstance.getClass().getInterfaces()[0];
            if(interfaceClass.getSimpleName().equalsIgnoreCase(interfaceName)){
                try {
                    return method.invoke(interfaceInstance, args);
                }catch (InvocationTargetException e){
                    Throwable targetException = e.getTargetException();
                    throw targetException;
                }
            }
        }
        return method.invoke(this, args);
    }
}
